<template>
  <view class="pet-container ">
    <view class="header animate__animated animate__fadeInDown">
      <view class="date-display">
        <picker mode="date" :value="currentDate" @change="onDateChange">
          <view>
            <text class="year">{{ currentDate }}</text>
          </view>
        </picker>
        <!-- <text class="week-info">{{ currentWeekInfo }}</text> -->

        <!-- 手动选择周数 -->
        <picker mode="selector" :range="weekOptions" @change="onWeekChange">
          <view class="week-selector">
            <text class="week-display">当前第{{ currentWeekNumber }}周 </text>
          </view>
        </picker>
      </view>

      <view class="nav-icons">
        <text :class="{ active: selected === '日' }" @click="goToDayView">日</text>
        <text :class="{ active: selected === '周' }" @click="selected = '周'">周</text>
        <view class="icon iconfont icon-shezhi" @click="goToSetting"></view>
        <view class="icon iconfont icon-xiazai" @click="goToImport"></view>
      </view>
    </view>



    <scroll-view scroll-y class="timetable-grid-container animate__animated animate__fadeInUp">
      <view class="timetable-grid">

        <view class="weekday-headers">
          <view class="time-col-header">{{ currentMonthDisplay }}</view>
          <view class="weekday-item" v-for="(day, index) in weekdays" :key="index"
            :class="{ active: index === activeDayIndex }">
            <text class="day-num">{{ day.label }}</text>
            <text class="date">{{ day.date }}</text>
          </view>
        </view>

        <view class="time-slots">
          <view class="time-slot" v-for="slot in timeSlots" :key="slot.id" :style="`grid-row: ${slot.id+1}`">
            <text class="slot-number">{{ slot.id }}</text>
            <text class="slot-time">{{ slot.time }}</text>
          </view>
        </view>

        <view class="schedule-columns">
          <view class="day-column" v-for="dayIndex in 7" :key="dayIndex">
            <CourseCard v-for="(course, idx) in allCourses.filter(c => c.day === dayIndex)" :key="idx" :course="course"
              @click="onCourseClick" />
            <!-- 值传入统一的course对象 -->
          </view>
        </view>
      </view>
    </scroll-view>

    <uni-popup ref="popup" type="center">
      <view class="popup-box">
        <view class="popup-title">
          <view class="popup-header">{{ selectedCourse.name }}</view>
          <view class="nav-icons">
            <view class="icon iconfont icon-a-shanchu1" @click="confirmDelete"></view>
            <view class="icon iconfont icon-xiugai" @click="modifyCourse"></view>
          </view>
        </view>

        <view class="popup-text">
          <view class="icon iconfont icon-qingjia"></view>节次:星期{{selectedCourse.day}} {{ periodTimeRange }}
        </view>
        <view class="popup-text">
          <view class="icon iconfont icon-jiaoyan"></view>老师:{{ selectedCourse.teacher }}
        </view>
        <view class="popup-text">
          <view class="icon iconfont icon-chengji"></view>地点:{{ selectedCourse.location }}
        </view>
        <view class="popup-text">
          <view class="icon iconfont icon-pingjiao"></view>性质:{{ selectedCourse.elective ? '必修' : '选修' }}
        </view>
      </view>
    </uni-popup>

    <AiSuggestionPopup :userId="userId" :week="currentWeekNumber" :dayOfWeek="activeDayIndex" />
  </view>
</template>

<script setup>
  import {
    onMounted,
    onUnmounted,
    watch
  } from 'vue'
  import {
    ref,
    computed
  } from 'vue'
  import {
    onShow
  } from "@dcloudio/uni-app"
  import {
    applyTheme,
    getCurrentTheme
  } from '@/utils/theme.js'; // 注意替换实际的 theme.js 路径

  // 初始化主题
  const initTheme = () => {
    const savedTheme = getCurrentTheme()
    const initialTheme = themeOptions.find(t => t.value === savedTheme) || themeOptions[0]
    if (initialTheme) {
      applyThemeVars(initialTheme.vars)
    }
  }

  // 应用主题变量
  const applyThemeVars = (vars) => {
    const doc = document.documentElement
    Object.entries(vars).forEach(([key, value]) => {
      doc.style.setProperty(key, value)
    })
  }

  // 生命周期钩子
  onMounted(() => {
    initTheme()

    // 监听主题变化事件
    uni.$on('themeChange', (newVars) => {
      applyThemeVars(newVars)
    })
  })

  onUnmounted(() => {
    // 移除事件监听
    uni.$off('themeChange')
  })

  const popup = ref(null)
  const selectedCourse = ref({})
  const selected = ref('周')
  const userId = uni.getStorageSync('userID');
  //颜色映射表
  onShow(() => {
    selected.value = '周'
  })
  const colorValues = ['#db806b', '#e9af63', '#f1d17a', '#a2b770', '#7a9db3', '#8a8ab1', '#b6dddc', '#9aa4a3',
    '#ae8c6a', '#f2ccd5'
  ]

  function mapColorById(courseId) {
    const index = courseId % colorValues.length
    return colorValues[index]
  }
  // 当前日期
  const currentDate = ref(getTodayDate())

  // 当前周数（可手动设置）
  const currentWeekNumber = ref(getWeekNumber(new Date(currentDate.value)))

  // 周数选项（1~20）
  const weekOptions = Array.from({
    length: 20
  }, (_, i) => `第${i + 1}周`)

  function onWeekChange(e) {
    const index = parseInt(e.detail.value)
    currentWeekNumber.value = index + 1
    request() // 获取该周的课程数据
  }

  // 课程数据
  const allCourses = ref([])
  //模拟数据
  const mockCourses = ref([{
    coursename: '微积分',
    teacher: '张三',
    location: '学武楼(1号楼) A306',
    color: 0,
    elective: false,
    courseId: 1,
    timeSlots: [{
        dayofweek: 1,
        period: 1
      },
      {
        dayofweek: 1,
        period: 2
      }
    ]
  }])


  //查找课程
  async function request() {
    try {
      const res = await uni.request({
        url: `http://47.122.53.1:80/course/week/${userId}/${currentWeekNumber.value}`,
        method: 'GET',
      })
      console.log('接口返回的data字段:', res.data.data);

      let dataObj = res.data.data

      let rawList = []

      if (dataObj && typeof dataObj === 'object' && !Array.isArray(dataObj)) { //判断传入的是什么数据类型
        rawList = Object.values(dataObj)
      } else if (Array.isArray(dataObj)) {
        rawList = dataObj
      }
      console.log('请求到的原始数据:', rawList)
      processRawCourses(rawList)




    } catch (err) {
      console.error('课程请求失败:', err)
      // 失败时用模拟数据
      processRawCourses(mockCourses.value)
    }
  }

  // 抽离的处理函数，格式化课程数据
  function processRawCourses(rawList) {
    const formattedCourses = [];
    rawList.forEach(item => {
      //如果这条课程没有 timeSlots（课程时间段）字段，或者是空数组，就跳过当前课程，继续下一个
      if (!item.timeSlots || item.timeSlots.length === 0) return;
      //创建一个空对象，用来将课程的节次按“星期几”（dayofweek）分类分组。
      const groupedByDay = {};

      item.timeSlots.forEach(slot => {
        //遍历课程的所有节次信息（timeSlots 数组中的每个时间段）。
        //取出当前节次对应的“星期几”（dayofweek）和“第几节课”（period），并转成数字。
        const day = Number(slot.dayOfweek);
        const period = Number(slot.period);
        //如果 day 或 period 不存在或不是数字，则跳过该节次。
        if (!day || !period || isNaN(day) || isNaN(period)) return;
        //如果 groupedByDay 里没有这个星期几的数组，就创建一个空数组；
        //然后把当前节次的课时 period 放进对应星期几的数组里。
        if (!groupedByDay[day]) groupedByDay[day] = [];
        groupedByDay[day].push(period);
      });
      //结束当前课程的节次遍历。
      //遍历 groupedByDay 对象里的每个属性，属性名是星期几（day），属性值是该天对应的所有课时数组（periods）。
      for (const [day, periods] of Object.entries(groupedByDay)) {
        //计算当天最早的节次，比如如果是第3和第4节课，则取3。
        const minPeriod = Math.min(...periods);
        //计算该天课程跨越的节次数量，即占多少个格子。
        const rowSpan = periods.length;
        // 将格式化后的课程对象放入 formattedCourses 数组。
        // 这里把课程名、地点、老师等信息原样带出；
        // color 通过函数 mapColorCodeToHex 转换成具体颜色值；
        // day 是星期几，转成数字；
        // rowStart 是课程开始的节次（最早的节次）；
        // rowSpan 是课程跨越的节数；
        // elective 是选修还是必修。
        formattedCourses.push({
          name: item.coursename,
          location: item.location,
          teacher: item.teacher,
          color: mapColorById(item.color),

          day: parseInt(day),
          rowStart: minPeriod,
          rowSpan: rowSpan,
          elective: item.elective,
          courseId: item.courseId, // ✅新增
        });
      }
    });
    //最后把处理好的课程数据赋值给响应式变量 allCourses，触发页面更新显示课程。
    console.log('格式化后的课程数据:', formattedCourses)
    allCourses.value = formattedCourses;
  }

  //删除课程
  function confirmDelete() {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除该课程当天的所有节次吗？',
      success(res) {
        if (res.confirm) {
          deleteCourseSlot()
        }
      }
    })
  }

  async function deleteCourseSlot() {
    const course = selectedCourse.value
    const courseId = course.courseId
    const week = currentWeekNumber.value
    const dayOfweek = course.day
    const startPeriod = course.rowStart
    const rowSpan = course.rowSpan

    // 构造要删除的所有节次
    const periodsToDelete = Array.from({
      length: rowSpan
    }, (_, i) => startPeriod + i)

    try {
      uni.showLoading({
        title: '删除中...'
      })
      // 并发发送删除请求
      await Promise.all(
        periodsToDelete.map(period =>
          uni.request({
            url: `http://47.122.53.1:80/course/timeslot/delete?courseId=${courseId}&week=${week}&dayOfweek=${dayOfweek}&period=${period}`,
            method: 'DELETE'

          })
        )
      )
      uni.hideLoading()
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      })
      popup.value.close()
      request() // 重新拉取课程数据

    } catch (err) {
      console.error('批量删除失败:', err)
      uni.showToast({
        title: '删除失败',
        icon: 'error'
      })
    }
  }

  //修改课程
  async function modifyCourse() {
    const course = selectedCourse.value
    const courseId = course.courseId
    const week = currentWeekNumber.value
    const dayOfweek = course.day
    const startPeriod = course.rowStart
    const rowSpan = course.rowSpan

    const periodsToDelete = Array.from({
      length: rowSpan
    }, (_, i) => startPeriod + i)

    try {
      uni.showLoading({
        title: '处理中...'
      })

      // 批量删除该课程当天所有节次
      await Promise.all(
        periodsToDelete.map(period =>
          uni.request({
            url: `http://47.122.53.1:80/course/timeslot/delete?courseId=${courseId}&week=${week}&dayOfweek=${dayOfweek}&period=${period}`,
            method: 'DELETE'
          })
        )
      )

      uni.hideLoading()
      uni.showToast({
        title: '课程已删除，准备修改',
        icon: 'success'
      })

      // 关闭详情弹窗
      popup.value.close()

      // 跳转到添加课程页面，并携带必要参数方便编辑（如课程ID、周、星期等）
      uni.switchTab({
        url: '/pages/index/add'
      })

    } catch (error) {
      uni.hideLoading()
      uni.showToast({
        title: '删除失败，无法修改',
        icon: 'error'
      })
      console.error('修改时删除失败:', error)
    }
  }




  request()

  const timeSlots = ref([{
      id: 1,
      time: '08:00\n08:45'
    },
    {
      id: 2,
      time: '08:55\n09:40'
    },
    {
      id: 3,
      time: '10:10\n10:55'
    },
    {
      id: 4,
      time: '11:05\n11:50'
    },
    {
      id: 5,
      time: '14:30\n15:15'
    },
    {
      id: 6,
      time: '15:25\n16:10'
    },
    {
      id: 7,
      time: '16:40\n17:25'
    },
    {
      id: 8,
      time: '17:35\n18:20'
    },
    {
      id: 9,
      time: '19:10\n19:55'
    },
    {
      id: 10,
      time: '20:00\n20:50'
    },
    {
      id: 11,
      time: '21:20\n22:15'
    }
  ])
  //弹窗显示节次
  const periodTimeRange = computed(() => {
    const startIndex = (selectedCourse.value.rowStart || 1) - 1
    const endIndex = startIndex + (selectedCourse.value.rowSpan || 1) - 1

    const start = timeSlots.value[startIndex]?.time?.split('\n')[0] || ''
    const end = timeSlots.value[endIndex]?.time?.split('\n')[1] || ''

    return start && end ? `${start}~${end}` : ''
  })

  const currentMonthDisplay = computed(() => {
    const parts = currentDate.value.split('/')
    return `${parseInt(parts[1])}月`
  })

  const weekdays = ref([])
  const currentWeekInfo = computed(() => getWeekInfo(currentDate.value))
  const activeDayIndex = computed(() => {
    const idx = weekdays.value.findIndex(day => day.fullDate === currentDate.value)
    return idx >= 0 ? idx : 0
  })

  generateWeekdays(currentDate.value)

  function onDateChange(e) {
    currentDate.value = e.detail.value.replace(/-/g, '/')
    generateWeekdays(currentDate.value)
  }

  function generateWeekdays(dateStr) {
    const date = new Date(dateStr)
    const day = date.getDay() || 7
    const monday = new Date(date)
    monday.setDate(date.getDate() - day + 1)

    const arr = []
    for (let i = 0; i < 7; i++) {
      const d = new Date(monday)
      d.setDate(monday.getDate() + i)
      arr.push({
        label: ['一', '二', '三', '四', '五', '六', '日'][i],
        date: `${d.getMonth() + 1}/${d.getDate()}`,
        fullDate: `${d.getFullYear()}/${pad(d.getMonth() + 1)}/${pad(d.getDate())}`
      })
    }
    weekdays.value = arr
  }

  function getTodayDate() {
    const d = new Date()
    return `${d.getFullYear()}/${pad(d.getMonth() + 1)}/${pad(d.getDate())}`
  }

  function getWeekInfo(dateStr) {
    const d = new Date(dateStr)
    const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekday = weekdayMap[d.getDay()]
    const weekNumber = getWeekNumber(d)
    return `第${weekNumber}周 ${weekday}`
  }

  // function getWeekNumber(date) {
  //   const start = new Date(date.getFullYear(), 0, 1)
  //   const diff = (date - start + (start.getTimezoneOffset() - date.getTimezoneOffset()) * 60000) / 86400000
  //   return Math.ceil((diff + start.getDay() + 1) / 7)
  // }
  function getWeekNumber(date) {
    const firstWeekStart = new Date('2025/06/02') // 固定第一周为 6月2日
    const msPerDay = 1000 * 60 * 60 * 24
    const diff = Math.floor((date - firstWeekStart) / msPerDay)
    return Math.floor(diff / 7) + 1
  }
  // 根据第几周、星期几（1=周一，7=周日）返回对应日期
  function getDateOfWeek(weekNumber, day = 1) {
    const base = new Date(FIRST_WEEK_START_DATE)
    base.setDate(base.getDate() + (weekNumber - 1) * 7 + (day - 1))
    return base
  }

  function formatDate(date) {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}/${m}/${d}`
  }

  // 监听 currentDate -> 自动更新 weekNumber
  watch(currentDate, (newVal) => {
    const dateObj = new Date(newVal)
    currentWeekNumber.value = getWeekNumber(dateObj)
  })

  // 监听 currentWeekNumber -> 自动更新 date（设置为该周的“周一”）
  watch(currentWeekNumber, (newVal) => {
    const monday = getDateOfWeek(newVal, 1) // 周1
    currentDate.value = formatDate(monday)
  })

  function pad(n) {
    return n < 10 ? '0' + n : n
  }

  function goToDayView() {
    selected.value = '日'
    uni.navigateTo({
      url: '/pages/index/day'
    })
  }

  function onCourseClick(course) {
    selectedCourse.value = course //// 就是点击的 course 对象
    popup.value.open()
  }

  function goToSetting() {
    uni.navigateTo({
      url: '/pages/index/setting'
    })
  }

  function goToImport() {
    uni.navigateTo({
      url: '/pages/index/import'
    })
  }
</script>

<style lang="scss">
  @import '../../UI/course-global.css';
  @import '../../static/iconfont/iconfont.css';
  @import '../../UI/animate.min.css';
  $header-height: 90rpx;
  $weekday-header-height: 80rpx;
  $time-col-width: 120rpx;
  $grid-row-height: 90rpx;




  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-image: var(--primary-color-dark);
    background-color: var(--primary-color);
    // border-bottom: 1px solid #eee;
    height: $header-height;

    border-radius: 16rpx; //边框圆角
    margin: 20rpx 10rpx; //外边距
    padding: 30rpx; //内边距
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 5rpx;

    .date-display {
      display: flex;
      flex-direction: column;

      .year {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .week-info {
        font-size: 24rpx;
        color: #999;
        margin-top: 5rpx;
      }

      .week-selector {
        margin-top: 10rpx;

        .week-display {
          font-size: 24rpx;
          color: #666;
        }
      }
    }

    .nav-icons {
      display: flex;
      align-items: center;

      text {
        font-weight: bold;
        margin-left: 30rpx;
        color: var(--sub-text-color);
      }

      text.active {
        color: var(--text-color); // 被选中时变色
      }

      .icon {
        font-size: 40rpx;
        color: #666;
        margin-left: 30rpx;
      }
    }
  }



  .timetable-grid-container {
    flex: 1;
    width: 100%;
    overflow-x: hidden; // 禁止左右滚动
    overflow-y: auto;
    background-color: var(--bg-color);
    position: relative;
    border-radius: 16rpx;
    margin: 20rpx 10rpx;
    padding: 20rpx 0rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 5rpx;
    border-right: 5px solid var(--border-color);



    .timetable-grid {
      display: grid;
      grid-template-columns: $time-col-width repeat(7, 1fr);
      grid-template-rows: auto repeat(11, $grid-row-height); // 第一行是header



      .weekday-headers {
        display: contents; // 使子元素直接参与 grid 布局




        .time-col-header {
          grid-column: 1;
          grid-row: 1;
          font-size: 28rpx;
          font-weight: bold;
          color: var(--text-color);
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: var(--primary-color);
          border-radius: 16rpx 0 0 0;




        }

        .weekday-item {
          grid-row: 1;
          text-align: center;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 10rpx 0;
          background-color: #fff;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
          border-bottom: 1px solid #cfcfcf;


          &.active {
            background-color: var(--bg-color);

            .day-num,
            .date {
              color: var(--sub-text-color);
              font-weight: bold;
            }
          }

          .day-num {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
          }

          .date {
            font-size: 22rpx;
            color: #999;
            margin-top: 5rpx;
          }
        }

        // 动态分配 grid-column
        .weekday-item:nth-child(2) {
          grid-column: 2;
        }

        .weekday-item:nth-child(3) {
          grid-column: 3;
        }

        .weekday-item:nth-child(4) {
          grid-column: 4;
        }

        .weekday-item:nth-child(5) {
          grid-column: 5;
        }

        .weekday-item:nth-child(6) {
          grid-column: 6;
        }

        .weekday-item:nth-child(7) {
          grid-column: 7;
        }

        .weekday-item:nth-child(8) {
          grid-column: 8;
        }
      }


      // 左边时间列
      .time-slots {
        grid-column: 1;
        grid-row: 1 / span 11;
        display: contents; // 让内部 time-slot 按 grid 渲染


        .time-slot {
          grid-column: 1;
          height: $grid-row-height;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 5rpx 0;
          box-sizing: border-box;
          border-right: 1px solid #cfcfcf;

          .slot-number {
            font-size: 24rpx;
            color: #666;
            font-weight: bold;
          }

          .slot-time {
            font-size: 20rpx;
            color: #999;
            text-align: center;
            white-space: pre-wrap;
            line-height: 1.2;
          }
        }
      }

      // 右边课程列
      .schedule-columns {
        grid-column: 2 / span 7;
        grid-row: 1 / span 11;
        display: contents; // 让每个课程块精确控制位置

        .day-column {
          display: contents;
        }
      }
    }
  }

  .popup-box {
    width: 100%;
    background-color: #fff;
    padding: 40rpx;
    border-radius: 24rpx;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    gap: 10rpx;


    .popup-title {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 10rpx;
      border-bottom: 1px solid #cfcfcf;
      margin-bottom: 10rpx;

      .popup-header {
        font-size: 34rpx;
        font-weight: bold;
        margin-bottom: 20rpx;
        text-align: center;
      }

      .nav-icons {
        display: flex;
        gap: 30rpx;
      }
    }



    .popup-text {
      font-size: 28rpx;
      color: #333;
      margin: 10rpx 0;
      display: flex;
      align-items: center;
      gap: 10rpx;
    }


  }
</style>